package com.whxy02.tolearn.app.interceptor;

import com.whxy02.tolearn.app.beans.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class AdminInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals("sessionID")) {
                    if(redisTemplate.opsForValue().get("user:"+cookie.getValue())!=null){
                        User user= (User) redisTemplate.opsForValue().get("user:"+cookie.getValue());
                        assert user != null;
                        if(user.getUserId()==1){
                            redisTemplate.expire("user:" + cookie.getValue(), 60 * 30, TimeUnit.SECONDS);
                            request.setAttribute("user", user);
                            cookie.setMaxAge(60 * 30);
                            response.addCookie(cookie);
                            return true;
                        }
                        else {
                            /**
                             * 刷新存储时间
                             */
                            response.sendRedirect(request.getContextPath()+"/401.html");
                            return false;
                        }
                    }
                }


            }

        }
        response.sendRedirect(request.getContextPath()+"/login.html");
        return false;

    }
}
